<template>
	<view class="page-main">
		<!-- <view class="topbox">
			<image class="topimg" :src="topBanner"></image>
			<view class="imgtext">你是一个完美主义者吗？</view>
		</view> -->
		<view class="line-progress">
			<u-line-progress :percentage="((currentIndex + 1) / totalNum) * 100" :showText="false" height="13"
				:activeColor="$store.state.primaryColor"></u-line-progress>
		</view>
		<swiper class="swipercard" previous-margin="0" next-margin="0" :circular="false" :autoplay="false"
			:current="currentIndex" @change="eventHandle">
			<block v-for="(item, index) in newQuestionsAnswer" :key="index">
				<swiper-item class="swiperitem">
					<view class="itembox">
						<!-- <view class="box-hd">
							<view class="hdname">当前第<view class="text1">{{ index+ 1}}</view>道题</view>
							<view class="hdnum">共{{totalNum}}道题</view>
						</view> -->
						<view class="contentbox">
							<!-- 类型：题目类型：1单选，2录音题目，3填空题 -->
							<view v-if="item.type == 1">
								<view class="boxtitle">
									<text class="textl">{{ index + 1 }}、</text>
									<text class="textr">{{ item.title || '' }}</text>
									<view v-html="formattedHtml(item.title_details)" style="margin-top: 20rpx"></view>
								</view>
								<view class="boxbody" v-for="(self, idxs) in item.basic" :key="idxs">
									<view class="chooseitem" @click="singChoose(index, idxs, self, item)">
										<image class="sinchoose-on" v-if="self.isSelect" :src="chooseonImg" mode="">
										</image>
										<view class="sinchoose" v-else></view>
										<view class="bodyr" v-if="self.image">
											{{ self.title || '' }}、
											<image :src="self.image" style="width: 100rpx; height: 100rpx"></image>
											{{ self.value || '' }}
										</view>
										<view class="bodyr" v-else>{{ self.title || '' }}、{{ self.value || '' }}</view>
									</view>
								</view>
							</view>
							<view v-if="item.type == 2">
								<view class="boxtitle">
									<text class="textl">{{ index + 1 }}、</text>
									<text class="textr">{{ item.title || '' }}</text>
									<view v-html="formattedHtml(item.title_details)" style="margin-top: 20rpx"></view>
								</view>
								<!-- <image class="_image" v-if="item.image" :src="item.image" mode="widthFix"></image> -->
								<view class="boxbody" v-for="(self, idxs) in item.basic" :key="idxs">
									<view class="chooseitem" @click="singChoose(index, idxs, self, item)">
										<image class="sinchoose-on" v-if="self.isSelect" :src="chooseonImg" mode="">
										</image>
										<view class="sinchoose" v-else></view>
										<view class="bodyr" v-if="self.image"
											style="align-items: center;display: flex;">
											<text>{{ self.title || '' }}、</text>
											<image class="_new_image" :src="self.image" mode="aspectFit"></image>
										</view>
										<view class="bodyr" v-else>{{ self.title || '' }}、{{ self.value || '' }}</view>
									</view>
								</view>
							</view>
							<view v-if="item.type == 3">
								<scroll-view :scroll-top="0" scroll-y="true" class="scroll-Y">
									<view class="boxtitle" style="display: flex">
										<text class="textl">{{ index + 1 }}、</text>
										<rich-text id="content" :selectable="true" :nodes="item.title_details"
											@itemclick="handleRichText(item, $event)"></rich-text>
										<!-- <view id="content" v-html="item.title_details" @click="handleRichText(item, $event)"></view> -->
									</view>
									<image class="_image" v-if="item.image" :src="item.image" mode="widthFix"></image>
									<view class="boxbody" v-for="(self, idxs) in item.basics" :key="idxs">
										<view class="chooseitem" @click="singChooseNew(index, idxs, self, item)">
											<image class="sinchoose-on" v-if="self.isSelect" :src="chooseonImg" mode="">
											</image>
											<view class="sinchoose" v-else></view>
											<view class="bodyr">{{ self.title || '' }}、{{ self.value || '' }}</view>
										</view>
									</view>
									<view v-if="item.basics_id">
										<text>空{{ item.basics_id }}已选择：{{ item[`basics_id_${Number(item.basics_id)}`] }}</text>
									</view>
								</scroll-view>
								
							</view>
							<view v-if="item.type == 'MULTY'">
								<view class="boxbody" v-for="(self, idxm) in item.basic" :key="idxm">
									<view class="chooseitem" @click="multyChoose(index, idxm)">
										<image class="sinchoose-on" v-if="self.isSelect" :src="chooseonImg2" mode="">
										</image>
										<view class="sinchoose sinchoose2" v-else></view>
										<view class="bodyr">{{ self.title || '' }}、{{ self.value || '' }}</view>
									</view>
								</view>
							</view>
							<view class="writeitem" v-if="item.type == 'QUESTION'">
								<textarea class="textInfo" v-model="item.userAnswer" @input="bindTextAreaBlur(index)"
									auto-height maxlength="200" placeholder="请输入您的答案" />
							</view>
						</view>
						<view class="footbtn">
							<view class="ftbtn1" @click="back(index)" v-if="index !== 0">上一题</view>
							<view class="ftbtn3" v-if="index + 1 < totalNum" @click="next(index)"
								:style="{ background: $store.state.buttonColor }">下一题</view>
							<view class="ftbtn2" v-else @click="submitData"
								:style="{ background: $store.state.buttonColor }">结束答题</view>
						</view>
					</view>
				</swiper-item>
			</block>
		</swiper>

		<u-popup :show="gbIshow" @close="gbIshow = false" @open="gbIshow = true" mode="center" round="20">
			<view class="NewBackpopupBody">
				<text class="title">恭喜答完啦！</text>
				<text
					class="content_text">一共答对{{ info.yes || 0 }}题，错了{{ info.no || 0 }}题当前等级为{{ info.level || '' }}</text>
				<view class="but_flex">
					<button class="rightButton" :style="{ background: $store.state.buttonColor }"
						@click="gbIshow = false">确定</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		props: {
			//问题列表数据
			dataList: {
				type: Array,
				default () {
					return [];
				}
			}
		},
		watch: {
			dataList: {
				deep: true,
				immediate: true,
				handler(newArr) {
					if (newArr.length) {
						this.newQuestionsAnswer = JSON.parse(JSON.stringify(newArr));
						this.totalNum = newArr.length;
						this.setEmptyData();
					}
				}
			},
			gbIshow: function(e) {
				if (e == false || e == 'false') {
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/Tabbar/Home/Home'
						});
					}, 1000);
				}
			}
		},
		data() {
			return {
				gbIshow: false,
				topBanner: require('../../static/banner.png'),
				chooseonImg: require('../../static/chooseon.png'),
				chooseonImg2: require('../../static/chooseon2.png'),
				totalNum: 0,
				currentIndex: 0,
				newQuestionsAnswer: [],
				formSubmitData: [], //提交所需数据
				element1: '',
				element2: '',
				reserve_id: 0,
				envetArrr: '',
				title_detailsArr: '',
				AnswerLibrary: [],
				info: {}
			};
		},
		mounted() {
			uni.$on('confirm', (e) => {
				this.info = {
					...e
				};
				this.gbIshow = true;
			});
		},
		onShow() {},
		methods: {
			formattedHtml(formattedContent) {
				return formattedContent.replace(/<img/g, '<img style="width: 100%;"');
			},
			handleRichText(item, e) {
				this.envetArrr = e;
				this.title_detailsArr = item.title_details;
				// console.log(this.currentIndex)
				if (this.newQuestionsAnswer[this.currentIndex].hasOwnProperty('result') == false) {
					// this.newQuestionsAnswer[this.currentIndex]['result'] =
				}

				this.$set(this.newQuestionsAnswer[this.currentIndex], 'basics', this.newQuestionsAnswer[this.currentIndex]
					.basic[Number(e.detail.node.attrs.id)]);
				this.$set(this.newQuestionsAnswer[this.currentIndex], 'basics_id', Number(e.detail.node.attrs.id));

				// console.log(this.newQuestionsAnswer[this.currentIndex])
				this.reserve_id = this.newQuestionsAnswer[this.currentIndex].basics_id;
				// console.log('eeeeeeeee', item.title_details)
				if (e.detail.node.name == 'a') {
					// console.log('111', e.detail.node.attrs.id)
				}
			},
			singChooseNew(j, e, self, item2) {
				// console.log(j)
				this.$set(this.newQuestionsAnswer[j], `basics_id_${this.newQuestionsAnswer[j].basics_id}`, this
					.newQuestionsAnswer[j].basics[e].title);
				if (this.newQuestionsAnswer[j].basics[e].isSelect) {
					this.newQuestionsAnswer[j].basics[e].isSelect = 0;
					this.formSubmitData[j].userAnswer = '';
				} else {
					for (var i = 0; i < this.newQuestionsAnswer[j].basics.length; i++) {
						if (this.newQuestionsAnswer[j].basics[i].isSelect) {
							this.newQuestionsAnswer[j].basics[i].isSelect = 0;
						}
					}
					this.newQuestionsAnswer[j].basics[e].isSelect = 1;
					// 这块结合业务逻辑可以进行优化处理
					// 例如只保存用户已选择答案Id等
					this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].basics[e];
					// console.log(this.formSubmitData[j].userAnswer)
					// console.log(this.newQuestionsAnswer[j].basics[e])
				}
				this.newQuestionsAnswer = JSON.parse(JSON.stringify(this.newQuestionsAnswer));
				let clickedElementId = this.envetArrr.target.node.attrs.id;
				console.log(this.envetArrr, 'this.envetArrr');
				console.log(this.newQuestionsAnswer[this.currentIndex].title_details);
				const regex = new RegExp(`<a id="${this.envetArrr.target.node.attrs.id}">([^<]*)</a>`);
				const newContent = `<a id="${this.envetArrr.target.node.attrs.id}">__${self.value}__</a>`;
				this.newQuestionsAnswer[this.currentIndex].title_details = this.newQuestionsAnswer[this.currentIndex]
					.title_details.replace(regex, newContent);
				// this.newQuestionsAnswer[this.currentIndex].title_details = updatedRichText
				// if (clickedElementId === '1') {
				// 	// console.log(this.envetArrr)
				// 	item2.id = item2.id + 'A'
				// 	if (this.envetArrr.target.node.name === 'a' && this.envetArrr.target.node.attrs.id === '1') {
				// 		let indexesToRemove = this.AnswerLibrary.reduce((acc, item, index) => {
				// 			if (item.id === item2.id) {
				// 				console.log(item.id)
				// 				acc.push(index)
				// 			}
				// 			return acc
				// 		}, [])
				// 		indexesToRemove.forEach(index => {
				// 			this.AnswerLibrary.splice(index, 1)
				// 			// this.formSubmitData[i].userAnswer = ''
				// 		})
				// 		this.AnswerLibrary.push({
				// 			userAnswer: self,
				// 			id: item2.id
				// 		})
				// 		if (this.newQuestionsAnswer[j].basics[e].isSelect) {
				// 			this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].basics[e]
				// 		}
				// 		// this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].basics[e]
				// 		console.log(this.newQuestionsAnswer[j].basics[e].isSelect)
				// 		console.log(this.formSubmitData[j])
				// 		console.log(this.AnswerLibrary)
				// 		this.newQuestionsAnswer[this.currentIndex].title_details = this.newQuestionsAnswer[this.currentIndex].title_details.replace(
				// 			/<a id='1'>(.*?)<\/a>/,
				// 			`<a id='1'>__${self.value}__</a>`
				// 		)
				// 		console.log(this.newQuestionsAnswer[this.currentIndex].title_details)
				// 	}
				// } else if (clickedElementId === '2') {
				// 	item2.id = item2.id + 'B'
				// 	if (this.envetArrr.target.node.name === 'a' && this.envetArrr.target.node.attrs.id === '2') {
				// 		let indexesToRemove = this.AnswerLibrary.reduce((acc, item, index) => {
				// 			if (item.id === item2.id) {
				// 				console.log(item.id)
				// 				acc.push(index)
				// 			}
				// 			return acc
				// 		}, [])
				// 		indexesToRemove.forEach(index => {
				// 			this.AnswerLibrary.splice(index, 1)
				// 			// this.formSubmitData[i].userAnswer = ''
				// 		})
				// 		this.AnswerLibrary.push({
				// 			userAnswer: self,
				// 			id: item2.id
				// 		})
				// 		if (this.newQuestionsAnswer[j].basics[e].isSelect) {
				// 			this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].basics[e]
				// 		}
				// 		console.log(this.newQuestionsAnswer[j].basics[e].isSelect)
				// 		console.log(this.formSubmitData[j])
				// 		console.log(this.AnswerLibrary)
				// 		this.newQuestionsAnswer[this.currentIndex].title_details = this.newQuestionsAnswer[this.currentIndex].title_details.replace(
				// 			/<a id='2'>(.*?)<\/a>/,
				// 			`<a id='2'>__${self.value}__</a>`
				// 		)
				// 	}
				// }
			},
			//创建提交数组的数据结构
			setEmptyData() {
				this.newQuestionsAnswer.forEach((res) => {
					let userAnswer = '';
					// console.log(res)
					if (res.type != 3) {
						res.basic &&
							res.basic.forEach((item) => {
								// console.log(item)
								if (!item.isSelect) item.isSelect = 0;
								else userAnswer = item;
							});
					} else {
						for (const group in res.basic) {
							res.basic[group].forEach((item) => {
								if (!item.isSelect) item.isSelect = 0;
								else userAnswer = item;
							});
						}
					}
					if (res.type == 'QUESTION') userAnswer = res.userAnswer;
					this.formSubmitData.push({
						id: res.id, //题目id
						userAnswer: userAnswer //答案
					});
				});
			},
			submitData() {
				console.log(this.AnswerLibrary);
				console.log(this.formSubmitData);
				for (var i = 0; i < this.formSubmitData.length; i++) {
					if (!this.formSubmitData[i].userAnswer) {
						let toast = '请完成第' + (i + 1) + '题后提交！';
						uni.showToast({
							title: toast,
							icon: 'none'
						});
						this.currentIndex = i;
						return;
					}
				}
				console.log(this.AnswerLibrary);
				this.$emit('submit', this.AnswerLibrary);
			},
			//单选事件
			singChoose(j, e, self, item2) {
				// 找到所有相同 id 的项的索引
				let indexesToRemove = this.AnswerLibrary.reduce((acc, item, index) => {
					if (item.id === item2.id) {
						acc.push(index);
					}
					return acc;
				}, []);

				// 从数组中移除所有相同 id 的项
				indexesToRemove.forEach((index) => {
					this.AnswerLibrary.splice(index, 1);
				});
				// 添加当前点击的项到 AnswerLibrary 数组中
				this.AnswerLibrary.push({
					userAnswer: self,
					id: item2.id
				});
				console.log(this.AnswerLibrary);
				if (this.newQuestionsAnswer[j].basic[e].isSelect) {
					this.newQuestionsAnswer[j].basic[e].isSelect = 0;
					this.formSubmitData[j].userAnswer = '';
				} else {
					for (var i = 0; i < this.newQuestionsAnswer[j].basic.length; i++) {
						if (this.newQuestionsAnswer[j].basic[i].isSelect) {
							this.newQuestionsAnswer[j].basic[i].isSelect = 0;
						}
					}
					this.newQuestionsAnswer[j].basic[e].isSelect = 1;
					// 这块结合业务逻辑可以进行优化处理
					// 例如只保存用户已选择答案Id等
					this.formSubmitData[j].userAnswer = this.newQuestionsAnswer[j].basic[e];
				}
				this.newQuestionsAnswer = JSON.parse(JSON.stringify(this.newQuestionsAnswer));
			},
			//多选事件
			multyChoose(j, e) {
				this.newQuestionsAnswer[j].basic[e].isSelect = this.newQuestionsAnswer[j].basic[e].isSelect ^ 1;
				let obj = [];
				for (var i = 0; i < this.newQuestionsAnswer[j].basic.length; i++) {
					if (this.newQuestionsAnswer[j].basic[i].isSelect) {
						// 这块结合业务逻辑可以进行优化处理
						// 例如 只保存用户已选择答案Id等
						// obj.push(this.newQuestionsAnswer[j].children[i].id)
						obj.push(this.newQuestionsAnswer[j].basic[i]);
					}
				}
				this.formSubmitData[j].userAnswer = obj;
				this.newQuestionsAnswer = JSON.parse(JSON.stringify(this.newQuestionsAnswer));
			},
			//富文本
			bindTextAreaBlur(index) {
				this.formSubmitData[index].userAnswer = this.newQuestionsAnswer[index].userAnswer;
			},
			//swiper改变时
			eventHandle(e) {
				// 这块可以结合业务逻辑进行优化处理，如左右滑动切换题目时做一些提示处理等
				this.currentIndex = e.detail.current;
			},
			// 上一题
			back(index) {
				if (!index) return;
				this.currentIndex = index - 1;
			},
			//下一题
			next(index) {
				if(this.newQuestionsAnswer[index].type == 3){
					for(var i=0,len=Object.keys(this.newQuestionsAnswer[index].basic).length; i<len; i++){
						if(this.newQuestionsAnswer[index][`basics_id_${i+1}`] == 'undefined' || this.newQuestionsAnswer[index][`basics_id_${i+1}`] == undefined){
							uni.showToast({
								title: `请完成第${index+1}大题第${i+1}个小空后在进行下一步！`,
								icon: 'none'
							});
							return false;
						}
					}
				}
				
				this.currentIndex = index + 1;
			}
		}
	};
</script>

<style scoped lang="scss">
	button::after {
		border: none;
	}
	
	.scroll-Y{
		width:100%;
		height:800rpx;
	}
	
	.page-main {
		width: 100%;
		height: 100vh;

		/deep/ .u-safe-bottom {
			display: none;
		}
	}

	._image {
		width: 100%;
		height: 280rpx;
	}

	._new_image {
		width: 200rpx;
		height: 200rpx;
	}

	.NewBackpopupBody {
		width: 536rpx;
		height: 440rpx;
		padding-top: 50rpx;
		padding-bottom: 50rpx;
		background-image: url('../../../../static/dati.png');
		background-repeat: no-repeat;
		background-size: 100% 100%;

		.title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 600;
			font-size: 36rpx;
			color: #333333;
			display: block;
			text-align: center;
			margin-top: 170rpx;
		}

		.content_text {
			width: 60%;
			margin: 0px auto;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 28rpx;
			color: #999999;
			display: block;
			text-align: center;
			padding-top: 30rpx;
			padding-bottom: 30rpx;
		}

		.but_flex {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.rightButton {
				width: 292rpx;
				height: 72rpx;
				font-family: PingFangSC, PingFang SC;
				font-weight: 600;
				font-size: 32rpx;
				color: #fff;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 50rpx;
				margin-top: 40rpx;
			}
		}
	}

	.textr {
		font-weight: 500;
		font-size: 32rpx;
		color: #333333;
	}

	.line-progress {
		width: 90%;
		margin: 0px auto;
		margin-top: 20rpx;
	}

	.topbox {
		width: 100%;
		height: 140rpx;
		position: relative;
	}

	.topbox .topimg {
		width: 100%;
		height: 100%;
	}

	.topbox .imgtext {
		position: absolute;
		bottom: 60rpx;
		left: 58rpx;
		font-size: 36rpx;
		font-weight: normal;
		color: #ffffff;
		line-height: 36rpx;
		text-shadow: 0rpx 2rpx 4rpx rgba(0, 0, 0, 0.5);
	}

	.swipercard {
		width: 100%;
		// height: calc(100vh - 316rpx);
		height: calc(100vh);
		background: #ffffff;
	}

	.itembox {
		width: calc(100% - 96rpx);
		padding: 32rpx 48rpx;
	}

	.box-hd {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 4rpx dashed #f0f0f0;
		padding-bottom: 16rpx;
		padding-left: 16rpx;
	}

	.hdname {
		width: 400rpx;
		font-size: 28rpx;
		display: flex;
		align-items: flex-start;
		font-weight: 500;
		color: #666666;
		line-height: 40rpx;
	}

	.text1 {
		color: #1fa474;
		font-size: 40rpx;
		line-height: 32rpx;
	}

	.hdnum {
		font-size: 28rpx;
		font-weight: 400;
		color: #666666;
		line-height: 42rpx;
	}

	.contentbox {
		font-size: 30rpx;
		color: #333333;
		margin-top: 48rpx;
	}

	.boxtitle .textl {
		width: 50rpx;
		height: 34rpx;
		/* background: linear-gradient(90deg, #C3FFDA 0%, #ffffff 100%); */
		/* background: linear-gradient( 90deg, #FDEDED 0%, #FDE4C8 100%); */
	}

	.boxbody {
		/* padding-left: 40rpx; */
		line-height: 64rpx;
		margin: 25rpx 0rpx 25rpx 0;
	}

	.chooseitem {
		display: flex;
		align-items: center;
		background: #f4f4f4;
		border-radius: 8rpx;
		border: 2rpx solid #dadada;
		padding-left: 20rpx;
		padding-top: 10rpx;
		padding-bottom: 10rpx;
	}

	.sinchoose {
		width: 28rpx;
		height: 28rpx;
		margin-right: 16rpx;
		border-radius: 50%;
		background: #ffffff;
		border: 2rpx solid #bfbdbd;
	}

	.sinchoose2 {
		border-radius: 6rpx;
	}

	.sinchoose-on {
		width: 32rpx;
		height: 32rpx;
		margin-right: 16rpx;
	}

	.writeitem textarea {
		min-height: 164rpx;
		margin: 24rpx auto;
		padding: 16rpx;
		border: 2rpx solid #ebebeb;
		border-radius: 4px;
		font-size: 30rpx;
		color: #333333;
	}

	.footbtn {
		display: flex;
		justify-content: space-between;
		margin-top: 112rpx;
		padding: 0 10rpx;
	}

	.ftbtn1 {
		width: 300rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		background-color: #efefef;
		font-size: 30rpx;
		font-weight: 500;
		border-radius: 50rpx;
		font-family: PingFangSC, PingFang SC;
		font-weight: 600;
		font-size: 32rpx;
		color: #333333;
	}

	.ftbtn2 {
		width: 300rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		/* background-color: #267ffe; */
		font-size: 30rpx;
		font-weight: 500;
		color: #ffffff;
		border-radius: 50rpx;
	}

	.ftbtn3 {
		width: 300rpx;
		height: 70rpx;
		line-height: 70rpx;
		text-align: center;
		/* background-color: #267ffe; */
		font-size: 30rpx;
		font-weight: 500;
		color: #ffffff;
		border-radius: 50rpx;
	}
</style>